package server

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order-server/basic/config"
	"order-server/internal/dao"
	"order-server/pkg"
	pb "order-server/proto"
	"strconv"
)

type Server struct {
	pb.UnimplementedOrderServer
}

func (s *Server) CartCreate(c context.Context, req *pb.CartCreateReq) (*pb.CartCreateResp, error) {
	cart := dao.Cart{
		GoodId: int(req.GoodId),
		Number: int(req.Number),
	}
	err := config.DB.Create(&cart).Error
	//虚拟库存存入redis
	key := "cart" + strconv.Itoa(int(req.GoodId))
	config.RDB.Set(key, req.Number, 0)
	if err != nil {
		return &pb.CartCreateResp{}, errors.New("购物车添加失败")
	}
	return &pb.CartCreateResp{}, nil
}

func (s *Server) OrderCreate(c context.Context, req *pb.OrderCreateReq) (*pb.OrderCreateResp, error) {
	key := "cart" + strconv.Itoa(int(req.GoodId))
	val := config.RDB.Get(key).Val()
	atoi, _ := strconv.Atoi(val)

	if int(req.Number) > atoi {
		return &pb.OrderCreateResp{Url: ""}, errors.New("库存不够")
	}
	var good dao.Good
	config.DB.Where("id=?", req.GoodId).First(&good)
	order := dao.Order{
		OrderSn: uuid.NewString(),
		Price:   good.Price,
		Status:  0,
	}
	err := config.DB.Create(&order).Error
	goodOrder := dao.GoodOrder{
		OrderId: int(order.ID),
		GoodId:  int(req.GoodId),
		Number:  int(req.Number),
	}
	err = config.DB.Create(&goodOrder).Error
	sprintf := fmt.Sprintf("%.2f", order.Price)
	alipay := pkg.Alipay("支付", order.OrderSn, sprintf)
	if err != nil {
		return &pb.OrderCreateResp{Url: ""}, errors.New("订单创建失败")
	}
	return &pb.OrderCreateResp{Url: alipay}, nil
}

func (s *Server) OrderShow(c context.Context, req *pb.OrderShowReq) (*pb.OrderShowResp, error) {
	var order dao.Order
	err := config.DB.Where("order_sn=?", req.Sn).First(&order).Error
	var goodOrder dao.GoodOrder
	err = config.DB.Where("order_id=?", order.ID).First(&goodOrder).Error
	var good dao.Good
	err = config.DB.Where("id=?", goodOrder.GoodId).First(&good).Error
	if err != nil {
		return &pb.OrderShowResp{
			Name:  "",
			Price: 0,
			Num:   0,
		}, errors.New("订单展示失败")
	}
	return &pb.OrderShowResp{
		Name:  good.Name,
		Price: float32(order.Price),
		Num:   int64(goodOrder.Number),
	}, nil
}
